import crypto from 'crypto';
import axios from 'axios';
import XLSX from 'xlsx';
// import fs from 'fs'
import { url, from, to, appid, salt, key } from './env/prod.js';

const translateBeforePath = 'translate-file/';
const translateAfterPath = 'after-translate/';
let countLine = 0;
const getExcelFileData = (fileName) => {
    // 如果乱码，可以使用这种方法改文档类型。如果文档加密，可能无法解析出来
    // const fileData = fs.readFileSync(translateBeforePath+fileName, 'binary');
    // const workbook = XLSX.read(fileData,{type:'binary',cellStyles:true});
    const workbook = XLSX.readFile(translateBeforePath + fileName);
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    countLine = jsonData.length;
    return jsonData
};

const outputExcelFileData = (outputData) => {
    const workbookNew = XLSX.utils.book_new();
    let worksheet_data = [];
    outputData.forEach((item) => {
        let lineDataArray = [];
        lineDataArray.push(item.src);
        lineDataArray.push(item.dst);
        worksheet_data.push(lineDataArray)
    })
    const worksheetNew = XLSX.utils.aoa_to_sheet(worksheet_data);
    XLSX.utils.book_append_sheet(workbookNew, worksheetNew, "Sheet1");
    const currentData = new Date().getTime();
    XLSX.writeFile(workbookNew, translateAfterPath + currentData + "_output.xlsx");
}


//默认翻译示例文档
const run = async (fileName = '翻译前.xls') => {
    let afterTranslateData = [];
    const excelData = getExcelFileData(fileName);
    excelData.forEach(async (before) => {
        // console.log(item);
        let password = appid + before.beforeTranslate + key;
        let md5 = crypto.createHash('md5');
        let passwordMD5 = md5.update(password).digest('hex');
        let param = 'q=' + before.beforeTranslate + '&from=' + from + '&to=' + to + '&appid=' + appid + '&salt=' + salt + '&sign=' + passwordMD5;
        let config = {
            method: 'get',
            maxBodyLength: Infinity,
            url: url + '?' + param,
            headers: {

            }
        };
        let vv = await axios.request(config);
        if (vv.data && vv.data.error_code && vv.data.error_code > 50000) {
            // console.log(vv.data);
            afterTranslateData.push({'src':"", 'dst': ''});
            if (countLine == afterTranslateData.length) {
                // console.log(afterTranslateData);
                outputExcelFileData(afterTranslateData);
            }
        } else {
            if (vv.data.trans_result[0]) {
                let result = vv.data.trans_result[0];
                afterTranslateData.push(result);
            }
            if (countLine == afterTranslateData.length) {
                // console.log(afterTranslateData);
                outputExcelFileData(afterTranslateData);
            }
        }

    });

}

run();